package com.softserveinc.moviedbapp.parser;

import android.util.Log;

import com.softserveinc.moviedbapp.model.MovieInfo;
import com.softserveinc.moviedbapp.util.MovieAppConstants;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class JSONParserMovieInfo implements IMovieDBMethodGetInfo {

	private InputStream is;

	private static final String TAG = JSONParserMovieInfo.class.getSimpleName();

	public JSONParserMovieInfo(final InputStream is) {
		this.is = is;
	}

	@Override
	public MovieInfo parseMovieInfo() {
		MovieInfo movieInfo = new MovieInfo();

		int retrys = MovieAppConstants.RETRY_COUNT;
		while (retrys > 0) {
			try {
				String jsonString = JSONHelper.convertStreamToString(is);

				JSONArray jsonArray = new JSONArray(jsonString);
				JSONObject movieInfoJson = jsonArray.getJSONObject(0);

				movieInfo.setMovieId(movieInfoJson.getInt("id"));
				movieInfo.setOverview(movieInfoJson.getString("overview"));
				movieInfo.setTrailerUrl(movieInfoJson.getString("trailer"));

				/* set movie's cast */
				JSONArray castJsonArray = movieInfoJson.getJSONArray("cast");
				JSONObject personJsonObject;
				List<String> cast = new ArrayList<String>();
				for (int i = 0; i < castJsonArray.length(); i++) {
					personJsonObject = castJsonArray.getJSONObject(i);

					if (personJsonObject.getString("job").equals("Actor")) {
						cast.add(personJsonObject.getString("name"));
					}
				}
				movieInfo.setCast(cast);

				/* set movie's backdrop image urls */
				JSONArray backdropJsonArray = movieInfoJson.getJSONArray("backdrops");
				JSONObject imageJsonObject;
				List<String> backdropImagesUrls = new ArrayList<String>();
				for (int i = 0; i < backdropJsonArray.length(); i++) {
					imageJsonObject = backdropJsonArray.getJSONObject(i).getJSONObject("image");

					if (imageJsonObject.getString("size").equals("thumb")) {
						backdropImagesUrls.add(imageJsonObject.getString("url"));
					}

				}
				movieInfo.setBackdropImagesUrls(backdropImagesUrls);

				Log.d(TAG, "JSON Parsing succeeded, movieInfo\n" + movieInfo.toString());
				break;
			} catch (JSONException e) {
				Log.e(TAG, "JSON Movie info parsing failed.", e);
				retrys--;
				continue;
			}
		}
		return movieInfo;

	}
}
